package filter;

import bean.User;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String[] noNeedAuthPage = new String[]{
                "home",
                "checkLogin",
                "register",
                "loginAjax",
                "login",
                "product",
                "category",
                "search"};
        String context = request.getContextPath();
        String uri = request.getRequestURI();
        uri = StringUtils.remove(uri,context);
        if(uri.startsWith("/fore")&&!uri.startsWith("/foreServlet"))
        {
            String method = StringUtils.substring(uri,5);
            if(!Arrays.asList(noNeedAuthPage).contains(method))
            {
                User user = (User) request.getSession().getAttribute("user");
                if(null==user)
                {
                    response.sendRedirect("login.jsp");
                    return;
                }
            }
        }
            filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
